package com.company.woye.onpackage.activity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bigkoo.pickerview.view.TimePickerView;
import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.onpackage.adapter.OnPackageListViewAdapter;
import com.company.woye.onpackage.entity.BestOnPackageEntity;
import com.company.woye.onpackage.entity.OnPackageListEntity;
import com.company.woye.onpackage.entity.OnSonPackageListEntity;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.DataUtils;
import com.company.woye.utils.ScannerManager;
import com.company.woye.utils.SharedPreferenceUtils;
import com.company.woye.utils.Toaster;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 对包
 */
public class OnPackageActivity extends BaseActivity implements OnPackageListViewAdapter.OnItemClickListener {

    @BindView(R.id.lv_on_package_summary)
    ListView summaryListView;
    @BindView(R.id.tv_on_package_sure)
    TextView tv_on_package_sure;
    @BindView(R.id.tv_on_package_search)
    TextView tv_on_package_search;
    @BindView(R.id.sp_on_package_deptname)
    Spinner sp_on_package_deptname;
    @BindView(R.id.sp_on_package_factory)
    Spinner sp_on_package_cJ;
    @BindView(R.id.sp_on_package_grop)
    Spinner sp_on_package_lsx;
    @BindView(R.id.tv_on_package_start_time)
    TextView tv_on_package_start_time;
    @BindView(R.id.tv_on_package_end_time)
    TextView tv_on_package_end_time;
    @BindView(R.id.ed_on_package_heyue)
    EditText ed_on_package_heyue;
    @BindView(R.id.ed_on_package_danbian)
    EditText ed_on_package_danbian;
    @BindView(R.id.ed_on_package_huo)
    TextView ed_on_package_huo;
    @BindView(R.id.ed_on_package_po)
    TextView ed_on_package_po;
    @BindView(R.id.sp_on_package_state)
    Spinner sp_on_package_task_state;
    @BindView(R.id.tv_on_package_best_on_package)
    TextView tv_on_package_best_on_package;
    @BindView(R.id.iv_on_package_back)
    ImageView ivOnPackageBack;
    @BindView(R.id.tv_on_package_back)
    TextView tvOnPackageBack;
    @BindView(R.id.edit_Barcode)
    EditText editBarcode;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.ll_on_package_summary)
    LinearLayout llOnPackageSummary;
    @BindView(R.id.rl_on_package_bottom)
    LinearLayout rlOnPackageBottom;
    @BindView(R.id.rl)
    RelativeLayout rl;

    private String deptName = "", cJname = "", LoginUserNo = "", FormType = "", OperType = "", lsxName = "";
    private String StationNo = "";
    private JSONArray deptJsonarray, cJnameJsonarray, LsxNameJsonArray, BestOnPackageJsonArry;
    private JSONArray masterJSONArray, detailJSONArray;
    private final int MSG_FIND_DEPT = 9001;
    private final int MSG_FIND_CJNAME = 9002;
    private final int MSG_FIND_LSXNAME = 9003;
    private final int MSG_FIND_LIST = 9004;
    private final int MSG_FIND_SON_LIST = 9005;
    private final int MSG_FIND_BEST_ON_PACKAGE = 9006;
    private final int MSG_ERROR = 9007;
    private List<String> deptNameList, cJnameList, LsxNameList, taskStateList;
    private ArrayAdapter<String> deptAdapter, cjNameAdapter, lsxNameAdapter, taskStateAdapter;
    private String TAG = getClass().getSimpleName();
    private TimePickerView timePickerView;
    private String TimeType = "";//1是开始时间  2 是结束时间
    private OnPackageListViewAdapter onPackageListViewAdapter;
    private List<OnPackageListEntity> onPackageListEntities = new ArrayList<>();
    private String SearchType = "1";
    boolean isSpinnerFirst = true;
    private ScannerManager scannerManager;
    //全局变量
    private ProgressDialog waitDialog = null;
    String ZydCode = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建对话框，
        waitDialog = new ProgressDialog(this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        getDepaName();
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_on_package;
    }

    @Override
    public void initView() {
        //部门车间默认登录的
        deptName = MyApplication.Bbm;
        cJname = MyApplication.CjName;
        LoginUserNo = MyApplication.curLoginUserNo;
        lsxName = MyApplication.DepartMent;
        FormType = TAG;
        if (((String) SharedPreferenceUtils.getData(sharedPreferences, "nowGongWei", "0")).equals("0")) {
            StationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "leftGongWei", "");
        } else {
            StationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "rightGongWei", "");
        }


        tv_on_package_start_time.setText(DataUtils.getNowData());
        tv_on_package_end_time.setText(DataUtils.getNowData());
        //点击查看详情
        onPackageListViewAdapter = new OnPackageListViewAdapter(this, onPackageListEntities, this);
        summaryListView.setAdapter(onPackageListViewAdapter);
        //获取部门
        //getDepaName();

        //任务状态
        taskStateList = new ArrayList<>();
        taskStateList.add("未开始");
        taskStateList.add("执行中");
        taskStateList.add("异常");
        taskStateList.add("已完成");
        taskStateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, taskStateList);
        sp_on_package_task_state.setAdapter(taskStateAdapter);
        // sp_on_package_task_state.initContent(taskStateList);



        editBarcode.setInputType(InputType.TYPE_NULL);
        editBarcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editBarcode.setInputType(InputType.TYPE_CLASS_TEXT);
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.showSoftInput(editBarcode, InputMethodManager.SHOW_FORCED);
            }
        });
        editBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    if ((event.getAction() == KeyEvent.ACTION_UP) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        SearchType = "2";
                        search(SearchType);
                        return true;
                    }
                }
                return false;
            }
        });
        editBarcode.requestFocus();
        editBarcode.requestFocusFromTouch();
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                String nowCode = dealCode(code).trim();
                if (nowCode.indexOf("$") > -1) {
                    ZydCode = nowCode;
                    //用的是点击查询的搜索
                    SearchType = "2";
                    search(SearchType);
                    editBarcode.setText(nowCode);
                } else System.out.println("nowCode:"+nowCode+"不是转移单....");
            }
        },editBarcode.getContext());
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    //保留英文和数字
    private String dealCode(String code) {
        return code.replaceAll("[^a-zA-Z0-9$%]", "");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //最优对包数目
        //if (SearchType.equals("1"))
//        System.out.println("onResume:"+SearchType);
        bestOnPackage();
        //search("2","GetZydInfo");
    }

    private void ReadSQLData(String sql, String type) {
        this.ReadSQLData(sql, type, 0);
    }

    private void ReadSQLData(String sql, String type, int position) {
        System.out.print("----存储过程:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * [{"RoleName":"管理员"},{"RoleName":"调度"},{"RoleName":"装框操作"},{"RoleName":"物流运转"},{"RoleName":"试装箱"}]
                     */
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(sql);
                    System.out.print("----返回结果：" + jsonArray);
                    //部门
                    if (type.equals("dept")) {
                        deptJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_DEPT;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //车间
                    if (type.equals("cJname")) {
                        cJnameJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_CJNAME;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //组别
                    if (type.equals("LsxName")) {
                        LsxNameJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_LSXNAME;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //获取列表
                    if (type.equals("Search")) {
                        masterJSONArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_LIST;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }

                    //获取列表
                    if (type.equals("searchDetail")) {
                        detailJSONArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_SON_LIST;
                        msg.arg1 = position;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //获取最优对包台
                    if (type.equals("BestOnPackage")) {
                        System.out.println("ReadSQLData:MSG_FIND_BEST_ON_PACKAGE");
                        BestOnPackageJsonArry = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_BEST_ON_PACKAGE;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }

                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = MSG_ERROR;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
//                    e.printStackTrace();
//                    System.out.print(e.toString());
                }

            }

        };
        new Thread(run).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (waitDialog != null && waitDialog.isShowing()) waitDialog.hide();
            switch (msg.what) {
                //获取部门
                case MSG_FIND_DEPT:
                    if (deptJsonarray != null && deptJsonarray.length() > 0) {
                        deptNameList = new ArrayList<>();
                        for (int i = 0; i < deptJsonarray.length(); i++) {
                            try {
                                deptNameList.add(deptJsonarray.optJSONObject(i).get("BbmName").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        deptAdapter = new ArrayAdapter<String>(OnPackageActivity.this, android.R.layout.simple_dropdown_item_1line, deptNameList);
                        sp_on_package_deptname.setAdapter(deptAdapter);
                        for (int i = 0; i < deptNameList.size(); i++) {
                            if (deptNameList.get(i).equals(deptName)) {
                                sp_on_package_deptname.setSelection(i);
                            }
                        }
                    }
                    //获取车间
                    getCjName();
                    break;
                //获取车间
                case MSG_FIND_CJNAME:
                    if (cJnameJsonarray != null && cJnameJsonarray.length() > 0) {
                        cJnameList = new ArrayList<>();
                        for (int i = 0; i < cJnameJsonarray.length(); i++) {
                            try {
                                cJnameList.add(cJnameJsonarray.optJSONObject(i).get("CjName").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        cjNameAdapter = new ArrayAdapter<String>(OnPackageActivity.this, android.R.layout.simple_dropdown_item_1line, cJnameList);
                        sp_on_package_cJ.setAdapter(cjNameAdapter);
                        sp_on_package_cJ.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                                if (isSpinnerFirst) {
//                                    //第一次初始化spinner时，不显示默认被选择的第一项即可
//                                    view.setVisibility(View.INVISIBLE) ;
//                                }
//                                isSpinnerFirst = false ;
                                getLsxName();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                    }
                    //获取组别
                    getLsxName();
                    break;
                //获取组别
                case MSG_FIND_LSXNAME:
                    if (LsxNameJsonArray != null && LsxNameJsonArray.length() > 0) {
                        LsxNameList = new ArrayList<>();
                        for (int i = 0; i < LsxNameJsonArray.length(); i++) {
                            try {
                                LsxNameList.add(LsxNameJsonArray.optJSONObject(i).get("lsx").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
//                        sp_on_package_lsx.initContent(LsxNameList);
                        lsxNameAdapter = new ArrayAdapter<String>(OnPackageActivity.this, android.R.layout.simple_dropdown_item_1line, LsxNameList);
                        sp_on_package_lsx.setAdapter(lsxNameAdapter);
                        for (int i = 0; i < LsxNameList.size(); i++) {
                            if (LsxNameList.get(i).equals(lsxName)) {
                                sp_on_package_lsx.setSelection(i);
                            }
                        }
                    }
                    break;
                //获取列表
                case MSG_FIND_LIST:
                    System.out.println("MSG_FIND_LIST");
                    if (masterJSONArray != null && masterJSONArray.length() > 0) {
                        Gson gson = new Gson();
                        onPackageListEntities.clear();
                        onPackageListEntities.addAll(gson.fromJson(String.valueOf(masterJSONArray), new TypeToken<List<OnPackageListEntity>>() {
                        }.getType()));
                        //获取明细;
                        searchDetail(SearchType);
                    }
                    break;
                //获取列表详情
                case MSG_FIND_SON_LIST:
                    System.out.println("MSG_FIND_SON_LIST:" + msg.arg1);
                    if (detailJSONArray != null && detailJSONArray.length() > 0) {
                        System.out.println("MSG_FIND_SON_LIST:A");
                        for (int i = 0; i < masterJSONArray.length(); i++) {
                            if (masterJSONArray.optJSONObject(i).has("ZydCode")) {
                                try {
                                    System.out.println("ZydCode:+" + masterJSONArray.optJSONObject(i).getString("ZydCode"));
                                    JSONArray tmpArray = getDetailJSON(detailJSONArray, masterJSONArray.optJSONObject(i).getString("ZydCode"));
                                    System.out.println("tmpArray:" + tmpArray.toString());
                                    Gson gson = new Gson();
                                    List<OnSonPackageListEntity> onSonPackageListEntity = gson.fromJson(String.valueOf(tmpArray), new TypeToken<List<OnSonPackageListEntity>>() {
                                    }.getType());
                                    onPackageListEntities.get(i).setSonPackageListEntityList(onSonPackageListEntity);
                                } catch (JSONException e) {
                                    System.out.println("MSG_FIND_SON_LIST:JSONException-" + e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (onPackageListEntities != null && onPackageListEntities.size() > 0) {
                            if (onPackageListEntities.size() == 1) {
                                Intent intent = new Intent(OnPackageActivity.this, OnPackageDetailActivity.class);
                                intent.putExtra("ZydCode", onPackageListEntities.get(0).getZydCode());
                                intent.putExtra("dept", sp_on_package_deptname.getSelectedItem().toString());
                                intent.putExtra("cj", onPackageListEntities.get(0).getCj_name());
                                intent.putExtra("lsx", onPackageListEntities.get(0).getLsx());
                                intent.putExtra("start_time", tv_on_package_start_time.getText());
                                intent.putExtra("end_time", tv_on_package_end_time.getText());
                                intent.putExtra("PortraitInfo", onPackageListEntities.get(0).getPortraitInfo());
                                if (onPackageListEntities.get(0).getSonPackageListEntityList() != null
                                        && onPackageListEntities.get(0).getSonPackageListEntityList().size() > 0) {
                                    intent.putExtra("Operator", onPackageListEntities.get(0).getSonPackageListEntityList().get(0).getOperator());
                                } else {
                                    Toaster.showLong(OnPackageActivity.this, "没有转移单明细,请刷新后重新选择!");
                                    return;
                                }
                                startActivity(intent);
                            } else {
                                //刷新数据;
                                summaryListView.setAdapter(onPackageListViewAdapter);
                            }
                        }
                        System.out.println("MSG_FIND_SON_LIST:B");
                        Toaster.showLong(OnPackageActivity.this, "获取成功");
                    }
                    break;
                //获取最优对包
                case MSG_FIND_BEST_ON_PACKAGE:
                    if (BestOnPackageJsonArry != null && BestOnPackageJsonArry.length() > 0) {
                        System.out.println("handel:MSG_FIND_BEST_ON_PACKAGE");
                        Gson gson = new Gson();
                        List<BestOnPackageEntity> bestOnPackageEntities = gson.fromJson(String.valueOf(BestOnPackageJsonArry), new TypeToken<List
                                <BestOnPackageEntity>>() {
                        }.getType());
                        if (bestOnPackageEntities != null && bestOnPackageEntities.size() > 0) {
                            BestOnPackageEntity bestOnPackageEntity = bestOnPackageEntities.get(0);
                            tv_on_package_best_on_package.setText("对包台:" + bestOnPackageEntity.getCheckBagCur() + ";对包数:" + bestOnPackageEntity.getCheckBagCurNum()
                                    + ";最优对包台:" + bestOnPackageEntity.getCheckBagBest() + ";对包数:" + bestOnPackageEntity.getCheckBagBestNum());
                        }
                    }
                    // search(SearchType,"SearchDepartNeed");
                    search(SearchType);
                    break;
                case MSG_ERROR:
                    Toaster.showLong(OnPackageActivity.this, "连接数据库失败");
                    break;
                default:
                    break;
            }
        }
    };

    //获取对应明细
    private JSONArray getDetailJSON(JSONArray bestOnDetailJsonArry, String zydCode) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < bestOnDetailJsonArry.length(); i++) {
            if (bestOnDetailJsonArry.optJSONObject(i).has("ZydCode")) {
                try {
                    if (bestOnDetailJsonArry.optJSONObject(i).getString("ZydCode").equals(zydCode)) {
                        jsonArray.put(bestOnDetailJsonArry.optJSONObject(i));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsonArray;
    }

    private void bestOnPackage() {
        OperType = "SearchCheckBagSum";
        String sqlFindLsxName = " EXEC AGV_Check_CheckBagSearch @FormType='" + FormType + "',@CurStationNo ='" + StationNo
                + "',@bbm='" + sp_on_package_deptname.getSelectedItem()
                + "',@cj_name='" + sp_on_package_cJ.getSelectedItem()
                + "',@NeedTaskState='" + sp_on_package_task_state.getSelectedItem()
                + "',@OperType='" + OperType + "',@UserNo='" + LoginUserNo + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(sqlFindLsxName, "BestOnPackage");

    }


    private void getLsxName() {
        //调用WebService过程并处理界面更新;
        OperType = "GetLsxName";
        String sqlFindLsxName = "EXEC  AGV_Basic_GetLsxName @UserNo ='" + LoginUserNo + "'" + ", @cj_name ='" + (cJnameList.size() > 0 ? sp_on_package_cJ.getSelectedItem() : "") + "', @FormType ='" + FormType + "'" + ", @OperType ='" + OperType + "'";
        ReadSQLData(sqlFindLsxName, "LsxName");
    }

    private void getDepaName() {
        OperType = "GetBbmName";
        String sqlFindDept = "EXEC  AGV_Basic_GetBbmName @UserNo ='" + LoginUserNo + "'" + ", @FormType ='" + FormType + "'" + ", @OperType ='" + OperType + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(sqlFindDept, "dept");
    }

    private void getCjName() {
        OperType = "GetSewCjName";
        String sqlFindcJname = "EXEC  AGV_Basic_GetSewCjName @UserNo ='" + LoginUserNo + "'" + ", @FormType ='" + FormType + "'" + ", @OperType ='" + OperType + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(sqlFindcJname, "cJname");

    }

    private void search(String Type) {
        //type 为1的时候是自动刷新  为2的时候是查询获取的
        if (waitDialog != null) {
            waitDialog.setMessage("准备获取转移单数据.....");
            waitDialog.show();
        }
        String sqlSearch = "";
        if (Type.equals("2")) {
            sqlSearch = "EXEC AGV_Check_CheckBagSearch @FormType='" + FormType + "',@bbm='" + sp_on_package_deptname.getSelectedItem() + "'" +
                    ",@cj_name='" + sp_on_package_cJ.getSelectedItem() + "',@lsx='" + sp_on_package_lsx.getSelectedItem() + "',@StartNeedDate='" +
                    "" + tv_on_package_start_time.getText().toString() + "',@EndNeedDate='" + tv_on_package_end_time.getText().toString() + "',@StyleNo='" +
                    ed_on_package_huo.getText().toString().trim() + "',@OrderNo='" + ed_on_package_heyue.getText().toString().trim() + "'," +
                    "@PO='" + ed_on_package_po.getText().toString().trim() + "',@DBH='" + ed_on_package_danbian.getText().toString().trim() + "'" +
                    ",@NeedTaskState='" + sp_on_package_task_state.getSelectedItem() + "',@CurStationNo ='" + StationNo + "',@ZydCode ='" + ZydCode + "',@OperType='SearchDepartNeed',@UserNo='" + LoginUserNo + "'";
        } else if (Type.equals("1")) {
            sqlSearch = "EXEC AGV_Check_CheckBagSearch @FormType='" + FormType + "',@CurStationNo ='" + StationNo + "',@bbm='" + sp_on_package_deptname.getSelectedItem()
                    + "',@cj_name='" + sp_on_package_cJ.getSelectedItem() + "',@OperType='SearchDepartNeed',@UserNo='" + LoginUserNo + "'";
        }
        //调用WebService过程并处理界面更新;
        ReadSQLData(sqlSearch, "Search");
    }

    //按条件获取明细
    private void searchDetail(String Type) {
        //type 为1的时候是自动刷新  为2的时候是查询获取的
        if (waitDialog != null) {
            waitDialog.setMessage("准备获取转移单明细数据.....");
            waitDialog.show();
        }
        String sqlSearch = "";
        if (Type.equals("2")) {
            OperType = "SearchDepartNeedDetail";
            sqlSearch = "EXEC AGV_Check_CheckBagSearch @FormType='" + FormType + "',@bbm='" + sp_on_package_deptname.getSelectedItem() + "'" +
                    ",@cj_name='" + sp_on_package_cJ.getSelectedItem() + "',@lsx='" + sp_on_package_lsx.getSelectedItem() + "',@StartNeedDate='" +
                    "" + tv_on_package_start_time.getText().toString() + "',@EndNeedDate='" + tv_on_package_end_time.getText().toString() + "',@StyleNo='" +
                    ed_on_package_huo.getText().toString().trim() + "',@OrderNo='" + ed_on_package_heyue.getText().toString().trim() + "'," +
                    "@PO='" + ed_on_package_po.getText().toString().trim() + "',@DBH='" + ed_on_package_danbian.getText().toString().trim() + "'" +
                    ",@NeedTaskState='" + sp_on_package_task_state.getSelectedItem() + "',@CurStationNo ='" + StationNo + "',@ZydCode ='" + ZydCode + "',@OperType='" + OperType + "',@UserNo='" + LoginUserNo + "'";
        } else if (Type.equals("1")) {
            OperType = "SearchAutoDepartNeedDetail";
            sqlSearch = "EXEC AGV_Check_CheckBagSearch @FormType='" + FormType + "',@CurStationNo ='" + StationNo + "',@bbm='" + sp_on_package_deptname.getSelectedItem()
                    + "',@cj_name='" + sp_on_package_cJ.getSelectedItem() + "',@OperType='" + OperType + "',@UserNo='" + LoginUserNo + "'";
        }
        //调用WebService过程并处理界面更新;
        ReadSQLData(sqlSearch, "searchDetail");
    }

    /*
    private void searchDetail(String ZydCode,int position){
        if (SearchType.equals("2")){
            OperType = "SearchDepartNeedMX";
        }else {
            OperType = "SearchAutoDepartNeedMX";
        }
        String sqlSearch = "EXEC AGV_Check_CheckBagSearch @FormType='"+FormType+"',@CurStationNo ='"+StationNo+"',@ZydCode='"+ZydCode+
             "',@OperType='"+OperType+"',@UserNo='"+LoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(sqlSearch, "searchDetail",position);
    }
    */
    @OnClick({R.id.tv_on_package_back,R.id.iv_on_package_back, R.id.tv_on_package_search, R.id.tv_on_package_start_time, R.id.tv_on_package_end_time})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_on_package_search:
                ZydCode = "";
                SearchType = "2";
                bestOnPackage();
                break;
            case R.id.tv_on_package_back:
            case R.id.iv_on_package_back:
                finish();
                break;
            case R.id.tv_on_package_start_time:
                TimeType = "1";
//                showTime();
                showDatePickDlg();
                break;
            case R.id.tv_on_package_end_time:
                TimeType = "2";
                //showTime();
                showDatePickDlg();
                break;

        }
    }

    public void showDatePickDlg() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(OnPackageActivity.this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String month;
                if ((monthOfYear + 1) < 10) {
                    month = "0" + (monthOfYear + 1);
                } else {
                    month = (monthOfYear + 1) + "";
                }
                if (TimeType.equals("1")) {
                    tv_on_package_start_time.setText(year + "-" + (month) + "-" + dayOfMonth);
                } else if (TimeType.equals("2")) {
                    tv_on_package_end_time.setText(year + "-" + (month) + "-" + dayOfMonth);
                }
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();

    }
//    private void showTime() {
//        timePickerView = new TimePickerBuilder(OnPackageActivity.this, new OnTimeSelectListener() {
//            @Override
//            public void onTimeSelect(Date date, View v) {//选中事件回调
//                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
//                if (TimeType.equals("1")){
//                    tv_on_package_start_time.setText(DataUtils.dateToString(date));
//                }else if (TimeType.equals("2")){
//                    tv_on_package_end_time.setText(DataUtils.dateToString(date));
//                }
//            }
//        }).setDecorView((RelativeLayout) findViewById(R.id.rl))//必须是RelativeLayout，不设置setDecorView的话，底部虚拟导航栏会显示在弹出的选择器区域
//                //年月日时分秒 的显示与否，不设置则默认全部显示
//                .setType(new boolean[]{true, true, true, false, false, false})
//                .setLabel("", "", "", "", "", "")
//                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                .setTitleText("选择日期")//标题文字
//                .setTitleSize(20)//标题文字大小
//                .setTitleColor(getResources().getColor(R.color.black))//标题文字颜色
//                .setCancelText("取消")//取消按钮文字
//                .setCancelColor(getResources().getColor(R.color.blue))//取消按钮文字颜色
//                .setSubmitText("确定")//确认按钮文字
//                .setSubmitColor(getResources().getColor(R.color.blue))//确定按钮文字颜色
//                .setContentTextSize(22)//滚轮文字大小
//                .setTextColorCenter(getResources().getColor(R.color.blue))//设置选中文本的颜色值
//                .setLineSpacingMultiplier(1.8f)//行间距
//                .setDividerColor(getResources().getColor(R.color.light_gray))//设置分割线的颜色
//                .setDate(Calendar.getInstance())
//                .build();
//        timePickerView.show();
//
//    }

    @Override
    public void onItemClick(int position) {
        System.out.println("onPackageListEntities:position-" + position + "-" + onPackageListEntities);
        if (position < onPackageListEntities.size()) {
            Intent intent = new Intent(OnPackageActivity.this, OnPackageDetailActivity.class);
            intent.putExtra("ZydCode", onPackageListEntities.get(position).getZydCode());
            intent.putExtra("dept", sp_on_package_deptname.getSelectedItem().toString());
            intent.putExtra("cj", onPackageListEntities.get(position).getCj_name());
            intent.putExtra("lsx", onPackageListEntities.get(position).getLsx());
            intent.putExtra("start_time", tv_on_package_start_time.getText());
            intent.putExtra("end_time", tv_on_package_end_time.getText());
            intent.putExtra("PortraitInfo", onPackageListEntities.get(position).getPortraitInfo());
            if (onPackageListEntities.get(position).getSonPackageListEntityList() != null
                    && onPackageListEntities.get(position).getSonPackageListEntityList().size() > 0) {
                intent.putExtra("Operator", onPackageListEntities.get(position).getSonPackageListEntityList().get(0).getOperator());
            } else {
                Toaster.showLong(OnPackageActivity.this, "没有转移单明细,请刷新后重新选择!");
                return;
            }
            startActivity(intent);
        } else {
            Toaster.showLong(OnPackageActivity.this, "数据异常,请刷新后重新选择!");
        }

    }
}
